import 'dart:async';

import 'package:bigegg/common/log/xmm_logcat.dart';
import 'package:bigegg/utils/audio/xmm_audio_session.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:get/get.dart';

class XmmAudioPlayer {
  FlutterSoundPlayer? _playerModule;

  StreamSubscription<PlaybackDisposition>? _onProgress;

  Future init() async {
    _playerModule = FlutterSoundPlayer();
    await _playerModule?.openPlayer().then((value){
      XmmXLogcat.d("XmmAudioPlayer init");
    });
    await _playerModule?.setSubscriptionDuration(const Duration(milliseconds: 100));
    XmmAudioSession.instance.initSession();
  }

  ///开始播放，这里做了一个播放状态的回调
  Future startPlayer(
    String path, {
    Function()? onFinished,
    Function(Duration duration, Duration position)? onProgress,
  }) async {
    try {
      if(_playerModule?.isOpen() != true){
        await init();
      }
      if (_playerModule?.isPlaying == true) {
        await stopPlayer();
      }
      //监听播放进度
      _onProgress = _playerModule?.onProgress?.listen((e) {
        onProgress?.call(e.duration, e.position);
      });
      await _playerModule?.startPlayer(
        fromURI: path,
        codec: Codec.mp3,
        whenFinished: () {
          XmmXLogcat.d("XmmAudioPlayer finish");
          stopPlayer();
          onFinished?.call();
        },
      );
    } catch (err) {
      err.printError;
    }
  }

  /// 结束播放
  Future stopPlayer() async {
    try {
      await _playerModule?.stopPlayer();
      cancelPlayerSubscriptions();
    } catch (err) {
      err.printError;
    }
  }

  /// 取消播放监听
  void cancelPlayerSubscriptions() {
    if (_onProgress != null) {
      _onProgress!.cancel();
      _onProgress = null;
    }
  }

  ///获取播放状态
  Future<PlayerState> getPlayState() async {
    return await _playerModule?.getPlayerState() ?? PlayerState.isStopped;
  }

  /// 释放播放器
  void release() async {
    try {
      await _playerModule?.closePlayer();
    } catch (e) {
      e.printError;
    }
  }
}
